package org.luxor.common.netty.protocol;

import io.netty.channel.Channel;
import io.netty.handler.timeout.IdleStateHandler;
import org.luxor.common.netty.config.ServerPipelineConfig;
import org.luxor.common.netty.config.properties.NettyServerProperties;
import org.luxor.common.netty.protocol.codec.NettyDecoder;
import org.luxor.common.netty.protocol.codec.NettyEncoder;
import org.luxor.common.netty.protocol.handler.IdleTimeoutHandler;
import org.luxor.common.netty.protocol.handler.MessagePrintHandler;
import org.luxor.common.netty.protocol.handler.connect.ConnectMessageHandler;
import org.luxor.common.netty.protocol.handler.connect.DisconnectMessageHandler;
import org.luxor.common.netty.protocol.handler.keepalive.PingMessageHandler;
import org.luxor.common.netty.protocol.handler.send.*;

import java.util.concurrent.TimeUnit;

/**
 * 默认客户端处理链(流水线)
 *
 * @author Mr.yan @date 2023/9/13
 */
public class NettyServerPipelineConfig extends ServerPipelineConfig {
    private NettyServerProperties nettyServerProperties;

    public NettyServerPipelineConfig(NettyServerProperties nettyServerProperties) {
        this.nettyServerProperties = nettyServerProperties;
    }

    @Override
    public NettyServerProperties serverProperties() {
        return this.nettyServerProperties;
    }

    @Override
    public void initChannel(Channel ch) throws Exception {
        // 启用SSL连接?
        if (nettyServerProperties.isStartTls()) {
            ch.pipeline().addFirst("ssl", sslContext(nettyServerProperties.getSsl()).newHandler(ch.alloc()));
        }
        // NettyMessage编码器
        ch.pipeline().addLast(new NettyEncoder());
        // NettyMessage解码器
        ch.pipeline().addLast(new NettyDecoder(nettyServerProperties.getPacketSizeMax()));
        // 日志打印
        if (nettyServerProperties.isDebug()) {
            ch.pipeline().addLast(new MessagePrintHandler(nettyServerProperties.getId()));
        }
        // 心跳机制
        if (nettyServerProperties.getKeepAliveTimeSeconds() > 0) {
            long readerIdleTime = nettyServerProperties.getKeepAliveTimeSeconds();
            ch.pipeline().addLast(new IdleStateHandler(readerIdleTime, 0, 0, TimeUnit.SECONDS));
            ch.pipeline().addLast(new IdleTimeoutHandler(nettyServerProperties.getId(), true));
        }
        ch.pipeline().addLast(new PingMessageHandler(nettyServerProperties.getId()));
        // 连接认证
        ch.pipeline().addLast(new ConnectMessageHandler(nettyServerProperties));
        ch.pipeline().addLast(new DisconnectMessageHandler());
        // 通信处理
        ch.pipeline().addLast(new SendMessageHandler());
        ch.pipeline().addLast(new SendAckMessageHandler());
        ch.pipeline().addLast(new SendRecMessageHandler());
        ch.pipeline().addLast(new SendRelMessageHandler());
        ch.pipeline().addLast(new SendCompMessageHandler());
    }

}
